package com.coda.clouddisk.controller.impl;

import com.coda.clouddisk.annotation.Loggable;
import com.coda.clouddisk.context.BaseContext;
import com.coda.clouddisk.controller.SuperController;
import com.coda.clouddisk.controller.inter.UserController;
import com.coda.clouddisk.entity.KesunReturn;
import com.coda.clouddisk.entity.User;
import com.coda.clouddisk.message.MessageContext;
import com.coda.clouddisk.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/clouddisk/user")
public class UserControllerImpl extends SuperController implements UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;
    @Override
    public Map<String, Object> convertData(Map<String, Object> data) {
        //判断数据是否为空
        if (CollectionUtils.isEmpty(data)){
            return null;
        }
        setSuperService(userServiceImpl);
        return data;
    }

    /**
     * 用户登录
     * @param
     * @return
     */
    @Override
    @PostMapping("/login")
    @Loggable("用户登录")
    public KesunReturn login(@RequestBody User user) {

        String token = userServiceImpl.login(user);
        KesunReturn kesunReturn = new KesunReturn();
        kesunReturn.setObj(token);
        kesunReturn.setMsg(MessageContext.SUCCESS_MSG);
        kesunReturn.setCode(MessageContext.SUCCESS_CODE);
        return kesunReturn;
    }

    /**
     * 注册
     * @param
     * @return
     */
    @Override
    @PostMapping("/register")
    @Loggable("用户注册")
    public KesunReturn Register(@RequestBody User user) {
        KesunReturn back = userServiceImpl.Register(user);
        return back;
    }

    /**
     * 编辑个人信息
     * @param data
     * @return
     */
    @Override
    public KesunReturn edit(@RequestBody Map<String, Object> data) {
        data.put("id", BaseContext.getCurrentId());
        data.put("password", DigestUtils.md5DigestAsHex(data.get("password").toString().getBytes()));
        return super.edit(data);
    }
}
